package com.chee.plant.log;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.*;

public class PlantLogger {
	private Logger _logger = null;
	private GregorianCalendar _nowLogDt = null;
	private Handler _handler = null;
	private String _logPath = "%h/";
	public PlantLogger(String loggerName){
		this._logger = Logger.getLogger(loggerName);
	}
	public void info(String msg){
		this.confirmLogFile();
		this._logger.info(msg);
	}
	public void warn(String msg){
		this.confirmLogFile();
		this._logger.warning(msg);
	}
	public void error(String msg){
		this.confirmLogFile();
		this._logger.severe(msg);
	}
	private void getHandler(String logFile){
		try {
			this._handler = new FileHandler(logFile,true);
			this._handler.setLevel(Level.ALL);
			this._handler.setFormatter(new PlantLogFormat());
			this._logger.addHandler(this._handler);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void confirmLogFile(){
		GregorianCalendar cal = new GregorianCalendar();
		String suffix = String.format("plant.log.%1$d.%2$d.%3$d", cal.get(Calendar.YEAR),cal.get(Calendar.MONTH)+1,
				cal.get(Calendar.DAY_OF_MONTH));
		String logFile = this._logPath + suffix;
		if(this._nowLogDt == null){
			this._nowLogDt = cal; this.getHandler(logFile);
		}else if(this._nowLogDt.get(Calendar.YEAR) != cal.get(Calendar.YEAR) ||
					this._nowLogDt.get(Calendar.MONTH) != cal.get(Calendar.MONTH) ||
					this._nowLogDt.get(Calendar.DAY_OF_MONTH) != cal.get(Calendar.DAY_OF_MONTH)){
			this._nowLogDt = cal;
			this._logger.removeHandler(this._handler);
			this.getHandler(logFile);
		}
	}
}
